package com.wangwen.wechatmp.controller;

import com.github.binarywang.wxpay.bean.request.WxPayOrderQueryRequest;
import com.github.binarywang.wxpay.bean.result.WxPayMicropayResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.wangwen.wechatmp.base.WxpayService;
import com.wangwen.wechatmp.pay.FacePayEntity;
import com.wangwen.wechatmp.pay.FacePayResult;
import com.wangwen.wechatmp.pay.MyMicroPayRequest;
import com.wangwen.wechatmp.utils.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author wangwei
 */
@Controller
@RequestMapping("/api/wechat")
public class PayController {

    @Autowired
    private WxpayService wxpayService;

    /**
     * 微信刷脸支付
     * @param request
     * @return
     */
    @PostMapping("/facePay")
    public FacePayResult facePay(@RequestBody FacePayEntity request){

        request.setSpbillCreateIp(request.getIp());

        // 构建签名参数
        SortedMap<String,Object> parameters = new TreeMap<String, Object>();

        if (StringUtils.isNotBlank(request.getSubAppId())){
            parameters.put("sub_appid",request.getSubAppId());
        }
        if (StringUtils.isNotBlank(request.getSubMchId())){
            parameters.put("sub_mch_id",request.getSubMchId());
        }

        parameters.put("appid", request.getAppid());
        parameters.put("mch_id", request.getMchId());
        parameters.put("body", "xfacePay");
        parameters.put("openid", request.getOpenid());
        parameters.put("face_code", request.getFaceCode());
        parameters.put("total_fee", request.getTotalFee());
        parameters.put("spbill_create_ip", request.getIp());
        parameters.put("nonce_str", request.getNonceStr());
        parameters.put("out_trade_no", request.getOutTradeNo());
        String characterEncoding = "UTF-8";
        String sign = XmlUtils.createSign(characterEncoding, parameters, null);
        request.setSign(sign);
        return wxpayService.facePay(request);
    }

    /**
     * 微信二维码扫码支付
     */
    @PostMapping("/microPay")
    public WxPayMicropayResult microPay(@RequestBody MyMicroPayRequest micropayRequest){

        return  wxpayService.microPay(micropayRequest);
    }

    /**
     * 订单查询
     * @param queryOrderInput
     * @return
     */
    @PostMapping("/queryMicroOrder")
    public WxPayOrderQueryResult queryMicroOrder(@RequestBody WxPayOrderQueryRequest queryOrderInput) {
        return wxpayService.queryMicroOrder(queryOrderInput);
    }
}
